<?php
/**
 * 上传文件控制器
 * @author ran.ran
 */
namespace api\controllers;

use Yii;
use services\models\UpFileData;
use yii\web\Controller;
use components\ExWebUploaderAction;
use yii\web\Response;
use common\helper\HashHelper;

class UploadController extends Controller
{

    public $enableCsrfValidation = false;
    public $layout = false;

    public $uid = 0;
    public $op_id = 0;
    private $is_login = false;
    
    public $thumb = false;//是否生成缩略图
    public $thumbWidth = '';
    public $thumbHeight = '';
    
    public $imageMaxSize = 2048000;//设置文件大小
    public $imagePathFormat = '';//设置文件路径格式
    public $imageAllowFiles = [];//设置文件格式
    
    public $fileMaxSize = 2048000;
    public $filePathFormat = '';//设置文件路径格式
    public $fileAllowFiles = [];//设置文件格式
    
    public function init()
    {
        parent::init();
        
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
        
        $params = Yii::$app->request->get();
        //上传来源判断
       /*  if(isset($params['time']) && isset($params['key'])) {
            if(HashHelper::validateDataUploadHash($params['key'], $params['time'])) {
                $this->is_login = true;
            }
        } */
        $this->is_login = true;
        
        //设置图片大小
        if(isset($params['s']) && is_numeric($params['s']) && $params['s'] <= Yii::$app->params['imageMaxSize']) {
            $this->imageMaxSize = $params['s'] * 1024 * 1000;
        }
        //设置图片是否生成缩略图
        if(isset($params['t']) && is_numeric($params['t']) &&  $params['t'] == 1) {
            $this->thumb  = true;
        }
        //设置缩略图的宽度
        if(isset($params['w']) && is_numeric($params['w']) && $this->thumb) {
            $this->thumbWidth = $params['w'];
        }
        //设置缩略图的高度
        if(isset($params['h']) && is_numeric($params['h']) && $this->thumb) {
            $this->thumbHeight = $params['h'];
        }
        
        //设置上传图片的路径及格式
        $this->imagePathFormat = Yii::$app->params['upfile'].'{yyyy}{mm}{dd}/{time}{rand:6}';
        $this->imageAllowFiles = [".png",".jpg",".jpeg",".gif",".bmp"];
        
        //设置上传文件的路径
        $this->filePathFormat = Yii::$app->params['uploadfile'].'{yyyy}{mm}{dd}/{time}{rand:6}';
        
    }
    
    /**
     * 即时上传文件，通过文件域的方式
     * 接受参数s，表示自定义上传图片大小，不能超过4M
     * 接受参数t，表示自定义是否生成缩略图
     * 接受参数w 表示生成缩略图的宽度
     * 接受参数h 表示生成缩略图的的高
     * @return boolean[]|string[]|number|string
     */
    public function actionWebupload()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        if(!$this->is_login) {
            return ['flag'=>false,'state'=>'上传来源出错'];
        }
        
        $webUploader = new ExWebUploaderAction('EdFHl1YhMw2IMKRj', $this);
        //图片文件配置
        $webUploader->config['imageMaxSize'] = $this->imageMaxSize;
        $webUploader->config['imageAllowFiles'] = $this->imageAllowFiles;
        $webUploader->config['imagePathFormat'] = $this->imagePathFormat;
        //缩略图
        $webUploader->thumb = $this->thumb;
        $webUploader->thumbWidth = $this->thumbWidth;
        $webUploader->thumbHeight = $this->thumbHeight;
        
        $res = $webUploader->run();

        //数据存入数据库
        $res['id'] = '';
        if ($res['flag']) {
            $res['id'] = $this->addFile($res);
        }
        
        /*
         * [
         * "flag"=>''     //true 表示上传成功，false失败
         *"state" => "",  //上传状态
         *"url" => "",    //返回的地址
         *"title" => "",  //新文件名
         *"original" => "",//原始文件名
         *"type" => "" //文件类型
         *"size" => "",//文件大小
         * ]
         */
        return $res;
    }

    /**
     * 上传base64文件
     * 接受参数s，表示自定义上传图片大小，不能超过4M
     * 接受参数t，表示自定义是否生成缩略图 1生成 其他生成
     * 接受参数w 表示生成缩略图的宽度
     * 接受参数h 表示生成缩略图的的高
     * @return string
     */
    public function actionUploadBase64()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        
        if(!$this->is_login) {
            return ['flag'=>false,'state'=>'上传来源出错'];
        } 
        
        $webUploader = new ExWebUploaderAction('EdFHl1YhMw2IMKRjjjj', $this);
        
        //设置默认为base64
        $webUploader->config['action'] = 'uploadscrawl';//指定为base64上传
        $webUploader->config['uploadType'] = 'base64';//指定base64方式
        //文件配置
        $webUploader->config['scrawlAllowFiles'] =  $this->imageAllowFiles;
        $webUploader->config['scrawlMaxSize'] =  $this->imageMaxSize;
        $webUploader->config['scrawlPathFormat'] =$this->imagePathFormat;
        //缩略图
        $webUploader->thumb = $this->thumb;
        $webUploader->thumbWidth = $this->thumbWidth;
        $webUploader->thumbHeight = $this->thumbHeight;
        
        $res = $webUploader->run();
        //数据存入数据库
        $res['id'] = '';
        if ($res['flag']) {
            $res['id'] = $this->addFile($res);
        }
        
        /*
         * [
         * "flag"=>''     //true 表示上传成功，false失败
         *"state" => "",  //上传状态
         *"url" => "",    //返回的地址
         *"title" => "",  //新文件名
         *"original" => "",//原始文件名
         *"type" => "" //文件类型
         *"size" => "",//文件大小
         * ]
         */
        return $res;

    }
    
    /**
     * 上传文件
     * 接受参数s，表示自定义上传图片大小，不能超过5M
     * @return string
     */
    public function actionUploadFile()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
    
        if(!$this->is_login) {
            return [
                'flag' => false,
                'state' => '上传来源出错'
            ];
        }
        $this->fileAllowFiles = [
            ".flv",
            ".swf",
            ".mkv",
            ".avi",
            ".rm",
            ".rmvb",
            ".mpeg",
            ".mpg",
            ".ogg",
            ".ogv",
            ".mov",
            ".wmv",
            ".mp4",
            ".webm",
            ".mp3",
            ".wav",
            ".mid",
            ".rar",
            ".zip",
            ".tar",
            ".gz",
            ".doc",
            ".docx",
            ".xls",
            ".xlsx",
            ".ppt",
            ".pptx",
            ".pdf",
            ".txt",
            ".md",
            ".xml",
            ".csv",
        ];
        
        $params = Yii::$app->request->get();
    
        if(isset($params['s']) && is_numeric($params['s']) && $params['s'] <= Yii::$app->params['fileMaxSize']) {
            $this->fileMaxSize = $params['s'] * 1024 * 1000;
        }
        
        $webUploader = new ExWebUploaderAction('EdFHl1YhMw2IMKRjjjj', $this);
        
        //设置模式为文件模式
        $webUploader->config['action'] = 'uploadfile';//指定为上传文件
        
        //文件配置
        $webUploader->config['filePathFormat'] =  $this->fileAllowFiles;
        $webUploader->config['fileMaxSize'] =  $this->fileMaxSize;
        $webUploader->config['filePathFormat'] =$this->filePathFormat;
    
        $res = $webUploader->run();
        
        //数据存入数据库
        $res['id'] = '';
        if ($res['flag']) {
            $res['id'] = $this->addFile($res);
        }
    
        /*
         * [
         * "flag"=>''     //true 表示上传成功，false失败
         *"state" => "",  //上传状态
         *"url" => "",    //返回的地址
         *"title" => "",  //新文件名
         *"original" => "",//原始文件名
         *"type" => "" //文件类型
         *"size" => "",//文件大小
         * ]
         */
        return $res;
    
    }
    
     private  function addFile($res) {
        
        $model = new UpFileData();
        $img = str_replace(Yii::$app->params['upfile'], '', $res['url']);
    
        $model->c_uri = $img;
        $model->uid = $this->uid;
        $model->title = $res['title'];
        $model->original = $res['original'];
        $model->size = $res['size'];
        $model->c_type = $res['type'];
        $model->op_id = 0;
        $model->db_time = date("Y-m-d H:i:s");
    
        if(!$model->save()) {
            return 0;
        } 
        
        return $model->id;
            
    }
    

}

?>